package com.fr.report.write.config;

import com.fr.base.ColumnRow;
import com.fr.base.ColumnRowRelated;
import com.fr.base.FRContext;
import com.fr.base.XMLable;
import com.fr.base.core.BaseCoreUtils;
import com.fr.base.core.Mapper;
import com.fr.base.core.antlr.ANTLRException;
import com.fr.base.xml.XMLPrintWriter;
import com.fr.base.xml.XMLReadable;
import com.fr.base.xml.XMLableReader;
import com.fr.data.DBFeedback;
import com.fr.data.NameSubmitJob;
import com.fr.data.SubmitJob;
import com.fr.data.core.DataUtils;
import com.fr.data.core.db.ColumnInformation;
import com.fr.data.core.db.DBUtils;
import com.fr.data.core.db.dml.Table;
import com.fr.data.core.db.dml.Where;
import com.fr.report.cellElement.Formula;
import com.fr.report.core.FormReport.Action;
import com.fr.report.io.xml.ReportXMLUtils;
import com.fr.report.parameter.Parameter;
import com.fr.report.script.Calculator;
import com.fr.report.script.ParameterMapNameSpace;
import com.fr.report.script.core.FArray;
import com.fr.report.script.core.parser.UtilEvalError;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

public abstract class DMLConfig
  implements XMLable, ColumnRowRelated
{
  public static final String XML_TAG = "DMLConfig";
  protected Table table = null;
  private List columnConfigList = new ArrayList();
  protected List submitJobList = new ArrayList();
  private transient ColumnInformation[] columnInformations = null;
  private static Mapper toName = new Mapper()
  {
    public Object map(int paramInt, Object paramObject, List paramList)
    {
      return ((ColumnConfig)paramObject).getColumnName();
    }
  };
  private static Mapper toValue = new Mapper()
  {
    public Object map(int paramInt, Object paramObject, List paramList)
    {
      return ((ColumnConfig)paramObject).getColumnValue();
    }
  };

  public Table getTable()
  {
    return this.table;
  }

  public void setTable(Table paramTable)
  {
    this.table = paramTable;
  }

  public void addColumnConfig(ColumnConfig paramColumnConfig)
  {
    this.columnConfigList.add(paramColumnConfig);
  }

  public int getColumnConfigCount()
  {
    return this.columnConfigList.size();
  }

  public ColumnConfig getColumnConfig(int paramInt)
  {
    return ((ColumnConfig)this.columnConfigList.get(paramInt));
  }

  public void clearColumnConfigs()
  {
    this.columnConfigList.clear();
  }

  public void addSubmitJob(NameSubmitJob paramNameSubmitJob)
  {
    this.submitJobList.add(paramNameSubmitJob);
  }

  public int getSubmitJobCount()
  {
    return this.submitJobList.size();
  }

  public NameSubmitJob getSubmitJob(int paramInt)
  {
    return ((NameSubmitJob)this.submitJobList.get(paramInt));
  }

  public void clearSubmitJobs()
  {
    this.submitJobList.clear();
  }

  public ColumnRow[] getRelatedColumnRows()
  {
    HashSet localHashSet = new HashSet();
    int i = 0;
    int j = getColumnConfigCount();
    while (i < j)
    {
      ColumnConfig localColumnConfig = getColumnConfig(i);
      Object localObject = localColumnConfig.getColumnValue();
      if (localObject instanceof ColumnRowRelated)
        localHashSet.addAll(Arrays.asList(((ColumnRowRelated)localObject).getRelatedColumnRows()));
      else if ((localObject instanceof String) && (((String)localObject).startsWith("=")))
        try
        {
          localHashSet.addAll(Arrays.asList(Calculator.relatedColumnRowArray((String)localObject)));
        }
        catch (ANTLRException localANTLRException)
        {
          FRContext.getLogger().log(Level.WARNING, localANTLRException.getMessage(), localANTLRException);
        }
      ++i;
    }
    return ((ColumnRow[])localHashSet.toArray(new ColumnRow[0]));
  }

  public void execute(Connection paramConnection, Calculator paramCalculator)
    throws Exception
  {
    ExtractionSubmitter localExtractionSubmitter = new ExtractionSubmitter(this, paramConnection);
    paramCalculator.extract(getRelatedColumnRows(), paramCalculator.getCurrentColumnRow(), localExtractionSubmitter);
  }

  public DBFeedback executeAndFeedback(Connection paramConnection, Calculator paramCalculator)
    throws Exception
  {
    ExtractionSubmitter localExtractionSubmitter = new ExtractionSubmitter(this, paramConnection, new DBFeedback());
    paramCalculator.extract(getRelatedColumnRows(), paramCalculator.getCurrentColumnRow(), localExtractionSubmitter);
    return localExtractionSubmitter.getFeedback();
  }

  private DMLColumnValues[] rebuildDMLConfig(Calculator paramCalculator)
    throws CloneNotSupportedException
  {
    Object[] arrayOfObject = new Object[getColumnConfigCount()];
    int i = 0;
    int j = getColumnConfigCount();
    while (i < j)
    {
      ColumnConfig localColumnConfig = getColumnConfig(i);
      arrayOfObject[i] = calculateColumnValue2DML(localColumnConfig.getColumnValue(), paramCalculator);
      ++i;
    }
    return extractByValues2Column(arrayOfObject);
  }

  private Object calculateColumnValue2DML(Object paramObject, Calculator paramCalculator)
  {
    if (paramObject instanceof Parameter)
      try
      {
        return paramCalculator.eval(((Parameter)paramObject).getName());
      }
      catch (UtilEvalError localUtilEvalError1)
      {
        FRContext.getLogger().log(Level.WARNING, localUtilEvalError1.getMessage(), localUtilEvalError1);
        return null;
      }
    if (paramObject instanceof ColumnRow)
      return paramCalculator.resolveVariable(paramObject);
    if (paramObject instanceof Formula)
      try
      {
        return paramCalculator.eval(((Formula)paramObject).getContent());
      }
      catch (UtilEvalError localUtilEvalError2)
      {
        FRContext.getLogger().log(Level.WARNING, localUtilEvalError2.getMessage(), localUtilEvalError2);
        return null;
      }
    if ((paramObject instanceof String) && (paramCalculator.getAttribute("$$_NEWCHAR") != null) && (paramCalculator.getAttribute("$$_ORIGINALCHAR") != null))
      try
      {
        return new String(((String)paramObject).getBytes((String)paramCalculator.getAttribute("$$_NEWCHAR")), (String)paramCalculator.getAttribute("$$_ORIGINALCHAR"));
      }
      catch (UnsupportedEncodingException localUnsupportedEncodingException)
      {
        FRContext.getLogger().log(Level.WARNING, localUnsupportedEncodingException.getMessage(), localUnsupportedEncodingException);
      }
    return paramObject;
  }

  protected DMLColumnValues[] extractByValues2Column(Object[] paramArrayOfObject)
    throws CloneNotSupportedException
  {
    DMLColumnValues localDMLColumnValues = new DMLColumnValues();
    ArrayList localArrayList = new ArrayList();
    localArrayList.add(localDMLColumnValues);
    addDMLConfig2List(localDMLColumnValues, 0, paramArrayOfObject, localArrayList);
    return ((DMLColumnValues[])localArrayList.toArray(new DMLColumnValues[localArrayList.size()]));
  }

  private void addDMLConfig2List(DMLColumnValues paramDMLColumnValues, int paramInt, Object[] paramArrayOfObject, List paramList)
    throws CloneNotSupportedException
  {
    if (paramInt >= paramArrayOfObject.length)
      return;
    Object localObject1 = paramArrayOfObject[paramInt];
    if (localObject1 instanceof FArray)
    {
      int i = 0;
      int j = ((FArray)localObject1).length();
      while (true)
      {
        if (i >= j)
          return;
        DMLColumnValues localDMLColumnValues = paramDMLColumnValues;
        Object localObject2 = ((FArray)localObject1).elementAt(i);
        if (i > 0)
        {
          localDMLColumnValues = (DMLColumnValues)localDMLColumnValues.clone();
          paramList.add(localDMLColumnValues);
        }
        localDMLColumnValues.set(paramInt, localObject2);
        addDMLConfig2List(localDMLColumnValues, paramInt + 1, paramArrayOfObject, paramList);
        ++i;
      }
    }
    paramDMLColumnValues.set(paramInt, localObject1);
    addDMLConfig2List(paramDMLColumnValues, paramInt + 1, paramArrayOfObject, paramList);
  }

  protected abstract void dmlSubmit(Connection paramConnection, Calculator paramCalculator, Object[] paramArrayOfObject, Map paramMap)
    throws SQLException;

  public void readXML(XMLableReader paramXMLableReader)
  {
    if (paramXMLableReader.isAttr())
    {
      clearColumnConfigs();
      clearSubmitJobs();
    }
    else if (paramXMLableReader.isChildNode())
    {
      String str = paramXMLableReader.getTagName();
      if ("Table".equals(str))
      {
        this.table = new Table();
        paramXMLableReader.readXMLObject(this.table);
      }
      else
      {
        Object localObject;
        if ("ColumnConfig".equals(str))
        {
          localObject = new ColumnConfig();
          paramXMLableReader.readXMLObject((XMLReadable)localObject);
          addColumnConfig((ColumnConfig)localObject);
        }
        else if ("NameSubmitJob".equals(str))
        {
          localObject = new NameSubmitJob();
          paramXMLableReader.readXMLObject((XMLReadable)localObject);
          addSubmitJob((NameSubmitJob)localObject);
        }
        else if ("SubmitJob".equals(str))
        {
          localObject = ReportXMLUtils.readSubmitJob(paramXMLableReader);
          if (localObject != null)
          {
            NameSubmitJob localNameSubmitJob = new NameSubmitJob();
            localNameSubmitJob.setSubmitJob((SubmitJob)localObject);
            addSubmitJob(localNameSubmitJob);
          }
        }
      }
    }
  }

  public void writeXML(XMLPrintWriter paramXMLPrintWriter)
  {
    if (this.table != null)
      this.table.writeXML(paramXMLPrintWriter);
    int i = 0;
    int j = getColumnConfigCount();
    while (i < j)
    {
      ColumnConfig localColumnConfig = getColumnConfig(i);
      if (localColumnConfig != null)
        localColumnConfig.writeXML(paramXMLPrintWriter);
      ++i;
    }
    i = 0;
    j = getSubmitJobCount();
    while (i < j)
    {
      getSubmitJob(i).writeXML(paramXMLPrintWriter);
      ++i;
    }
  }

  protected Where generateWhere(Connection paramConnection, Calculator paramCalculator, Object[] paramArrayOfObject)
  {
    Where localWhere = null;
    for (int i = 0; i < getColumnConfigCount(); ++i)
    {
      ColumnConfig localColumnConfig = getColumnConfig(i);
      if (!(localColumnConfig.isKey()))
        break label78:
      if (localWhere == null)
        localWhere = new Where();
      String str = localColumnConfig.getColumnName();
      int j = getColumnType(str, paramConnection);
      localWhere.addColumn(str, j, 0, paramArrayOfObject[i]);
    }
    label78: return localWhere;
  }

  protected int getColumnType(String paramString, Connection paramConnection)
  {
    checkColumnTypes(paramConnection);
    for (int i = 0; i < this.columnInformations.length; ++i)
      if (paramString.equalsIgnoreCase(this.columnInformations[i].getColumnName()))
        return this.columnInformations[i].getColumnType();
    return 0;
  }

  private void checkColumnTypes(Connection paramConnection)
  {
    if (this.columnInformations == null)
    {
      String str = DataUtils.createSelectSQL(this.table);
      try
      {
        this.columnInformations = DBUtils.checkInColumnInformation(paramConnection, str, 0);
      }
      catch (Exception localException)
      {
        FRContext.getLogger().warning(localException.getMessage());
        this.columnInformations = new ColumnInformation[0];
      }
    }
  }

  public String toString()
  {
    StringBuffer localStringBuffer = new StringBuffer();
    int i = getColumnConfigCount();
    if (i > 0)
      localStringBuffer.append("(").append(BaseCoreUtils.join(BaseCoreUtils.map(this.columnConfigList, toName), ", ")).append(") values(").append(BaseCoreUtils.join(BaseCoreUtils.map(this.columnConfigList, toValue), ", ")).append(")");
    return localStringBuffer.toString();
  }

  public Object clone()
    throws CloneNotSupportedException
  {
    int i;
    DMLConfig localDMLConfig = (DMLConfig)super.clone();
    if (this.table != null)
      localDMLConfig.table = ((Table)this.table.clone());
    if (this.columnConfigList != null)
    {
      localDMLConfig.columnConfigList = new ArrayList();
      for (i = 0; i < getColumnConfigCount(); ++i)
        localDMLConfig.addColumnConfig((ColumnConfig)getColumnConfig(i).clone());
    }
    if (this.submitJobList != null)
    {
      localDMLConfig.submitJobList = new ArrayList();
      for (i = 0; i < this.submitJobList.size(); ++i)
        localDMLConfig.submitJobList.add(getSubmitJob(i).clone());
    }
    return localDMLConfig;
  }

  static DMLColumnValues[] access$000(DMLConfig paramDMLConfig, Calculator paramCalculator)
    throws CloneNotSupportedException
  {
    return paramDMLConfig.rebuildDMLConfig(paramCalculator);
  }

  protected static class DMLColumnValues
    implements Serializable, Cloneable
  {
    private ArrayList values = new ArrayList();

    protected void set(int paramInt, Object paramObject)
    {
      while (paramInt >= this.values.size())
        this.values.add(null);
      this.values.set(paramInt, paramObject);
    }

    protected Object get(int paramInt)
    {
      return this.values.get(paramInt);
    }

    protected int size()
    {
      return this.values.size();
    }

    protected Object[] toArray()
    {
      return this.values.toArray();
    }

    public Object clone()
      throws CloneNotSupportedException
    {
      DMLColumnValues localDMLColumnValues = (DMLColumnValues)super.clone();
      localDMLColumnValues.values = new ArrayList();
      int i = 0;
      int j = size();
      while (i < j)
      {
        localDMLColumnValues.set(i, BaseCoreUtils.cloneObject(get(i)));
        ++i;
      }
      return localDMLColumnValues;
    }
  }

  private class ExtractionSubmitter
    implements FormReport.Action
  {
    private DBFeedback feedback;
    private Connection conn;
    private final DMLConfig this$0;

    ExtractionSubmitter(, Connection paramConnection)
    {
      this(paramDMLConfig, paramConnection, null);
    }

    ExtractionSubmitter(, Connection paramConnection, DBFeedback paramDBFeedback)
    {
      this.this$0 = paramDMLConfig;
      this.conn = paramConnection;
      this.feedback = paramDBFeedback;
    }

    public DBFeedback getFeedback()
    {
      return this.feedback;
    }

    public void run(, Calculator paramCalculator)
      throws Exception
    {
      HashMap localHashMap = null;
      if ((this.feedback != null) || (this.this$0.getSubmitJobCount() > 0))
        localHashMap = new HashMap();
      DMLConfig.DMLColumnValues[] arrayOfDMLColumnValues = DMLConfig.access$000(this.this$0, paramCalculator);
      for (int i = 0; i < arrayOfDMLColumnValues.length; ++i)
      {
        this.this$0.dmlSubmit(this.conn, paramCalculator, arrayOfDMLColumnValues[i].toArray(), localHashMap);
        if (this.feedback != null)
          this.feedback.addFeedback(localHashMap);
        ParameterMapNameSpace localParameterMapNameSpace = ParameterMapNameSpace.create(localHashMap);
        paramCalculator.pushNameSpace(localParameterMapNameSpace);
        int j = 0;
        int k = this.this$0.getSubmitJobCount();
        while (j < k)
        {
          this.this$0.getSubmitJob(j).getSubmitJob().doJob(paramCalculator);
          ++j;
        }
        paramCalculator.removeNameSpace(localParameterMapNameSpace);
      }
    }
  }
}